package cn.charmaine.basic.interceptor;

import cn.charmaine.basic.annotation.PreAuthorize;
import cn.charmaine.basic.jwt.*;
import cn.charmaine.org.domain.Logininfo;
import cn.charmaine.system.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    @Value("${jwt.rsa.pub}")
    private String jwtRsaPublic;


    /**
     * @param request  经过spring封装的请求对象
     * @param response 经过spring封装的响应对象
     * @param handler  指controller的@Controller注解下的完整方法名
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拿到请求头，判断请求是否存在
        String token = request.getHeader("TOKEN");
        //从redis查询此token是否存在
//        Object logininfo = redisTemplate.opsForValue().get(token);
        if (token != null) {
            //获取公钥
            PublicKey publicKey = RsaUtils
                    .getPublicKey(FileCopyUtils
                    .copyToByteArray(this.getClass().getClassLoader().getResourceAsStream(jwtRsaPublic)));
            //解密得到payload
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            UserInfo userInfo = payload.getUserInfo();
            Logininfo lf = userInfo.getLogininfo();
            if (lf != null) {
//                Logininfo lf = (Logininfo) logininfo;
                if (lf.getType() != 1) {//如果不是主站用户
                    HandlerMethod method = (HandlerMethod) handler;//强转
                    PreAuthorize methodAnnotation = method.getMethodAnnotation(PreAuthorize.class);
                    if (methodAnnotation != null) {
                        String value = methodAnnotation.value();//dept:deleteById
//                        List<String> sns = permissionMapper.selectSnByLogininfoId(lf.getId());
                        List<String> sns = userInfo.getPermissions();
                        //判断这个人拥有的所有sn中是否包含了他请求的sn
                        if (!sns.contains(value)) {
                            response.setCharacterEncoding("UTF-8");//告诉浏览器页面的编码方式
                            response.setContentType("application/json;charset=UTF-8");//告诉服务器请求的编码方式
                            //获取写出流
                            PrintWriter out = response.getWriter();
                            //给前端信息请求被拦截
                            out.write("{\"success\":false,\"message\":\"noPermission\"}");
                            out.flush();//刷新
                            out.close();//关流
                            //不放行
                            return false;
                        }
                    }
                }
                //存在，刷新过期时间
                //redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
                //放行
                return true;
            }
        }
        //token为空，需要返回给前端消息
        //设置编码格式
        response.setCharacterEncoding("UTF-8");//告诉浏览器页面的编码方式
        response.setContentType("application/json;charset=UTF-8");//告诉服务器请求的编码方式
        //获取写出流
        PrintWriter out = response.getWriter();
        //给前端信息请求被拦截
        out.write("{\"success\":false,\"message\":\"noUser\"}");
        out.flush();//刷新
        out.close();//关流
        //不放行
        return false;
    }
}
